package facetest.az26;

import org.junit.Test;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * All rights Reserved, Designed By www.rongdasoft.com
 *
 * @version V1.0
 * @Title: PipedInputTest
 * @Description:
 * @author:wsp
 * @date: 2019/10/12
 * @Copyright: 2019/10/12 www.rongdasoft.com
 * Inc. All rights reserved.
 */
public class PipedInputTest {
    static Thread t1, t2;
    String[] zimuArr = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", ",M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
    String[] numArr = new String[zimuArr.length];


    {
        for (int i = 0; i < zimuArr.length; i++) {
            numArr[i] = (i + 1) + "";
        }

    }

    @Test
    public void test() throws IOException {
        PipedInputStream i1 = new PipedInputStream();
        PipedInputStream i2 = new PipedInputStream();
        PipedOutputStream o1 = new PipedOutputStream();
        PipedOutputStream o2 = new PipedOutputStream();
        i1.connect(o2);
        i2.connect(o1);
        String msg = "Your Turn";


        t1 = new Thread(() -> {
            byte[] buffer = new byte[9];
            for (String s : zimuArr) {
                try {
                    i1.read(buffer);
                    if (new String(buffer).equals(msg)) {
                        System.out.println(s);
                    }
                    o1.write(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }


        });
        t2 = new Thread(() -> {
            byte[] buffer = new byte[9];
            for (String s : numArr) {
                try {
                    o2.write(msg.getBytes());
                    i2.read(buffer);
                    if (new String(buffer).equals(msg)) {
                        System.out.println(s);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }

        });
        t1.start();
        t2.start();

        while (true) ;
    }
}
